<template>
  <a-modal
    title="新增报工表"
    width="80%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="工单编号" :labelCol="labelCol_T" :wrapperCol="wrapperCol_T" has-feedback>
              <a-select
                show-search
                option-filter-prop="children"
                :filter-option="
                  (input, option) => {
                    return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                "
                @change="workOrderIdChange"
                allowClear
                style="width: 100%"
                placeholder="请选择工单编号"
                v-decorator="['workOrderId', { rules: [{ required: true, message: '请选择工单！' }] }]"
              >
                <a-select-option
                  v-for="(item, index) in list.orderIdList"
                  :key="index"
                  :value="item.id"
                  :disabled="item.status !== 0"
                >{{ item.workOrderNo }}
                  {{ item.proName }}
                  <a-statistic v-if="item.status === -1" :value-style="{ fontSize: '15px' }" value="状态 : 未开始" />
                  <a-statistic
                    v-if="item.status === 0"
                    :value-style="{ fontSize: '15px', color: '#3f8600' }"
                    value="状态 : 执行中"
                  />
                  <a-statistic
                    v-if="item.status === 1"
                    :value-style="{ fontSize: '15px', color: '#cf1322' }"
                    value="状态 : 已结束"
                  />
                  <a-statistic
                    v-if="item.status === -2"
                    :value-style="{ fontSize: '15px', color: '#800080' }"
                    value="状态 : 已取消"
                  />
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId')">
            <a-form-item label="任务工序" :labelCol="labelCol_T" :wrapperCol="wrapperCol_T" has-feedback>
              <a-select
                show-search
                option-filter-prop="children"
                :filter-option="
                  (input, option) => {
                    return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                "
                @change="taskIdChange"
                style="width: 100%"
                placeholder="请选择任务工序"
                v-decorator="['taskId', { rules: [{ required: true, message: '请选择任务工序！' }] }]"
              >
                <a-select-option
                  v-for="(item, index) in list.taskIdList"
                  :key="index"
                  :value="item.id"
                  :disabled="item.status !== 0"
                >
                  <a-popover placement="left">
                    <span role="img" :aria-label="item.workStepName">
                      <a-tag v-if="item.workStepName">{{ item.workStepName }}</a-tag>
                      <a-tag v-if="item.sortNum" color="green">顺序 : {{ item.sortNum }}</a-tag>
                    </span>
                    <template slot="content" v-if="hasPerm('task:edit') & editEnable">
                      <a-radio-group placeholder="请选择任务状态" v-model="item.status" @change="selectStatus(item)">
                        <a-radio :value="-1">未开始</a-radio>
                        <a-radio :value="0">执行中</a-radio>
                        <a-radio :value="1" :disabled="item.status === -1">已结束</a-radio>
                      </a-radio-group>
                    </template>
                  </a-popover>
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId') && form.getFieldValue('taskId')">
            <a-form-item
              label="生产人员"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              extra="为空默认当前用户"
              has-feedback
            >
              <user-select
                placeholder="请选择生产人员"
                v-decorator="['productionUser', { rules: [{ message: '请选择生产人员！' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId') && form.getFieldValue('taskId')">
            <a-form-item label="报工数量" :labelCol="labelCol_T" :wrapperCol="wrapperCol_T" has-feedback>
              <a-input-number
                :min="0"
                v-decorator="['reportNum', { rules: [{ required: false, message: '请输入报工数量！' }] }]"
                @change="
                  (val) => {
                    form.setFieldsValue({
                      goodNum: val - form.getFieldValue('badNum'),
                      badNum: form.getFieldValue('reportNum') - form.getFieldValue('goodNum'),
                    })
                  }
                "
                style="width: 100%"
                placeholder="请输入报工数量"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId') && form.getFieldValue('taskId')">
            <a-form-item label="良品数量" :labelCol="labelCol_T" :wrapperCol="wrapperCol_T" has-feedback>
              <a-input-number
                @change="
                  (val) => {
                    form.setFieldsValue({
                      badNum: form.getFieldValue('reportNum') - val,
                    })
                  }
                "
                v-decorator="['goodNum', { rules: [{ required: false, message: '请输入良品数量！' }] }]"
                style="width: 100%"
                placeholder="请输入良品数量"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId') && form.getFieldValue('taskId')">
            <a-form-item label="不良品数" :labelCol="labelCol_T" :wrapperCol="wrapperCol_T" has-feedback>
              <a-input-number
                @change="
                  (val) => {
                    form.setFieldsValue({
                      reportNum: form.getFieldValue('goodNum') + val,
                    })
                  }
                "
                style="width: 100%"
                placeholder="请输入不良品数"
                v-decorator="['badNum', { rules: [{ required: false, message: '请输入良品数量！' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="36">
          <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId') && form.getFieldValue('taskId')">
            <a-form-item label="工作时间" :labelCol="labelCol_T" :wrapperCol="wrapperCol_T" has-feedback>
              <a-range-picker
                style="width: 100%"
                :show-time="{ format: 'HH:mm' }"
                :ranges="{ 当天: [moment('08:30', 'HH:mm'), moment('17:30', 'HH:mm')] }"
                format="YYYY-MM-DD HH:mm"
                :placeholder="['开始时间', '结束时间']"
                v-decorator="['startEndTime', { rules: [{ required: true, message: '请输入工作时间！' }] }]"
                @change="workTimeChange"
              />
            </a-form-item>
          </a-col>
          <a-col>
            <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId') && form.getFieldValue('taskId')">
              <a-form-item label="工作时长" :labelCol="labelCol_T" :wrapperCol="wrapperCol_T">
                <a-form-item
                  style="display: inline-flex"
                ><a-input
                  style="width: 80%"
                  type="number"
                  v-decorator="['workHour', { initialValue: 9 }]"
                  @change="workHourChange"
                  oninput="if(value<0)value=0;if(value>8640)value=8640"
                /><span style="padding-left: 2%">小时</span></a-form-item
                >
                <a-form-item
                  style="display: inline-flex"
                ><a-input
                  style="width: 80%"
                  type="number"
                  v-decorator="['workMoment', { initialValue: 0 }]"
                  @change="workMomentChange"
                  oninput="if(value<0)value=0;if(value>59)value=59"
                /><span style="padding-left: 2%">分钟</span></a-form-item
                >
              </a-form-item>
            </a-col>
          </a-col>
        </a-row>
        <a-form-item label="备注信息" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-textarea placeholder="请输入备注" v-decorator="['remarks']" :auto-size="{ minRows: 3, maxRows: 6 }" />
        </a-form-item>
      </a-form>
      <a-row :gutter="24" style="margin: 60px">
        <a-col :md="4" :sm="24" v-show="curTask">
          <a-statistic v-if="curTask.status === -1" title="工序状态" value="未开始" />
          <a-statistic
            v-if="curTask.status === 0"
            title="工序状态"
            :value-style="{ color: '#3f8600' }"
            value="执行中"
          />
          <a-statistic
            v-if="curTask.status === 1"
            title="工序状态"
            :value-style="{ color: '#cf1322' }"
            value="已结束"
          />
        </a-col>

        <a-col :md="4" :sm="24" v-show="!$utils.isEmpty(curTask) && !$utils.isUndefined(curTask.plaNum) && !$utils.isUndefined(curTask.goodNum)">
          <a-statistic
            title="工序进度"
            :value-style="{ color: curTask.goodNum + form.getFieldValue('goodNum') < curTask.plaNum ? '#3f8600' : '#cf1322',}"
            :value="curTask.goodNum + '+' + form.getFieldValue('goodNum')"
          >
            <template #suffix>
              <span> / {{ curTask.plaNum }}</span>
            </template>
          </a-statistic>
        </a-col>
      </a-row>
    </a-spin>
  </a-modal>
</template>

<script>
import moment from 'moment'
import { workReportAdd } from '@/api/modular/main/workreport/workReportManage'
import { workOrderList } from '@/api/modular/main/workorder/workOrderManage'
import { taskEdit, taskList } from '@/api/modular/main/task/taskManage'
import UserSelect from '@/components/MyComp/UserSelect'
import TaskSelect from '@/components/MyComp/TaskStatusSelect'

export default {
  components: {
    UserSelect,
    TaskSelect
  },
  props: {
    editEnable: {
      type: Boolean,
      default: true,
      required: false
    }
  },
  data() {
    return {
      curTask: '',
      list: {
        orderIdList: [],
        taskIdList: []
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },

      labelCol_T: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol_T: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      startEndTimeString: '',
      startEndTimeArray: [],
      endTimePicker: '',
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this)
    }
  },
  methods: {
    selectStatus(values) {
      taskEdit(values)
        .then((res) => {
          if (res.success) {
            this.$message.success('状态修改成功')
            this.confirmLoading = false
            this.$emit('ok', values)
          } else {
            this.$message.error(res.message)
          }
        })
        .finally((res) => {
          this.confirmLoading = false
        })
    },
    moment,
    workOrderIdChange(val) {
      // 将相关数据置空

      this.form.setFieldsValue({
        taskId: null
      })
      this.curTask = {}
      taskList({ workOrderId: val }).then((res) => {
        this.list.taskIdList = res.data
      })
    },
    taskIdChange(val) {
      this.curTask = this.$utils.find(this.list.taskIdList, (item) => item.id === val)
    },
    // 初始化方法
    add(record) {
      this.visible = true
      workOrderList().then((res) => {
        this.list.orderIdList = res.data
      })
      this.mulBadItemData = this.$options.filters['dictData']('bad_item')

      this.$nextTick(() => {
        this.form.setFieldsValue({
          reportNum: 0,
          goodNum: 0,
          badNum: 0
        })
        this.form.getFieldDecorator('startEndTime', {
          initialValue: [moment('08:30', 'HH:mm'), moment('17:30', 'HH:mm')]
        })
        this.startEndTimeString = [
          moment('08:30', 'HH:mm', 'YYYY-MM-DD HH:mm').format('YYYY-MM-DD HH:mm'),
          moment('17:30', 'HH:mm', 'YYYY-MM-DD HH:mm').format('YYYY-MM-DD HH:mm')
        ].join(';')
        this.endTimePicker = this.startEndTimeString.split(';')[1]
      })
    },
    // 修改时间选择器
    workTimeChange(date, dateStrArr) {
      this.endTimePicker = dateStrArr[1]
      this.$nextTick(() => {
        this.form.setFieldsValue({
          workHour: Math.floor(moment(dateStrArr[1]).diff(dateStrArr[0]) / (1000 * 60) / 60),
          workMoment: (moment(dateStrArr[1]).diff(dateStrArr[0]) / (1000 * 60)) % 60
        })
        this.startEndTimeString = dateStrArr.join(';')
      })
    },
    // 修改工作时长——时
    workHourChange() {
      this.$nextTick(() => {
        this.startEndTimeArray = this.startEndTimeString.split(';')
        this.startEndTimeArray[0] = moment(this.startEndTimeArray[0], 'YYYY-MM-DD HH:mm:ss')
        this.startEndTimeArray[1] = moment(this.startEndTimeArray[0]).add(this.form.getFieldValue('workHour'), 'hours')
        this.startEndTimeArray[1] = moment(this.startEndTimeArray[1]).add(this.form.getFieldValue('workMoment'), 'minutes')
        this.endTimePicker = moment(this.startEndTimeArray[1]).subtract(this.form.getFieldValue('workMoment'), 'minutes')
        this.form.setFieldsValue({
          startEndTime: this.startEndTimeArray
        })
        this.startEndTimeString = [
          moment(this.startEndTimeArray[0]).format('YYYY-MM-DD HH:mm'),
          moment(this.startEndTimeArray[1]).format('YYYY-MM-DD HH:mm')
        ].join(';')
      })
    },
    // 修改工作时长——分
    workMomentChange() {
      this.$nextTick(() => {
        this.startEndTimeArray = this.startEndTimeString.split(';')
        this.startEndTimeArray[0] = moment(this.startEndTimeArray[0], 'YYYY-MM-DD HH:mm:ss')
        this.startEndTimeArray[1] = moment(this.endTimePicker).add(this.form.getFieldValue('workMoment'), 'minutes')
        this.form.setFieldsValue({
          startEndTime: this.startEndTimeArray
        })
        this.startEndTimeString = [
          moment(this.startEndTimeArray[0]).format('YYYY-MM-DD HH:mm'),
          moment(this.startEndTimeArray[1]).format('YYYY-MM-DD HH:mm')
        ].join(';')
      })
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          if (values.mulBadItem) {
            values.mulBadItem = values.mulBadItem.join(';')
          }
          for (const key in values) {
            if (typeof values[key] === 'object' && values[key] != null) {
              values[key] = JSON.stringify(values[key])
            }
          }
          values.startEndTime = this.startEndTimeString || null
          values.workTime = values.workHour * 60 + parseInt(values.workMoment)
          workReportAdd(values)
            .then((res) => {
              if (res.success) {
                this.$message.success('新增成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error(res.message) // + res.message
              }
            })
            .finally((res) => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.curTask = {}
      this.startEndTimeString = ''
      this.form.getFieldDecorator('startEndTime', { initialValue: null })
      this.form.resetFields()
      this.visible = false
    }
  }
}
</script>
